package com.guli.coupon.service.impl;

import com.guli.common.utils.R;
import com.guli.common.vo.CouponVo;
import com.guli.common.vo.MemberRespVo;
import com.guli.coupon.dto.PublishCouponDto;
import com.guli.coupon.entity.CouponHistoryEntity;
import com.guli.coupon.interceptor.LoginInterceptor;
import com.guli.coupon.service.CouponHistoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.coupon.dao.CouponDao;
import com.guli.coupon.entity.CouponEntity;
import com.guli.coupon.service.CouponService;
import org.springframework.util.CollectionUtils;


@Service("couponService")
public class CouponServiceImpl extends ServiceImpl<CouponDao, CouponEntity> implements CouponService {

    @Autowired
    private CouponHistoryService couponHistoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CouponEntity> page = this.page(
                new Query<CouponEntity>().getPage(params),
                new QueryWrapper<CouponEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public boolean publishCoupon(PublishCouponDto publishCouponDto) {
        //根据id查询出优惠卷信息
        CouponEntity coupon = this.getById(publishCouponDto.getId());
        //优惠卷不存在
        if (coupon == null) {
            throw new RuntimeException("优惠卷暂不存在");
        }
        //优惠卷存在
        //设置发布状态
        coupon.setPublish(1);
        boolean isUpdate = this.updateById(coupon);
        if (isUpdate) {
            return true;
        }
        return false;
    }

    @Override
    public R getCoupon(Long couponId) {
        //根据couponId查询当前优惠卷
        CouponEntity coupon = this.getById(couponId);
        MemberRespVo memberRespVo = LoginInterceptor.memberRespThreadLocal.get();
        //获取每个用户限领张数
        Integer perLimit = coupon.getPerLimit();
        //从sms_coupon_history表查询该用户领取是否达到上限
        int count = couponHistoryService.count(new QueryWrapper<CouponHistoryEntity>()
                .eq("member_id", memberRespVo.getId()).eq("coupon_id", coupon.getId()));
        if (count >= perLimit) {
            return R.ok("本次优惠卷领取已到达上限");
        }
        Integer memberLevel = coupon.getMemberLevel();
        if (memberLevel != 0 || memberRespVo.getLevelId() < memberLevel) {
            return R.error("等级不够，不能领取该优惠卷");
        }
        Integer receiveCount = coupon.getReceiveCount();
        Integer publishCount = coupon.getPublishCount();
        boolean update = this.update().set("receive_count", receiveCount + 1)
                .lt("receive_count", publishCount).update();
        if (update) {
            //记录到优惠卷领取记录表
            CompletableFuture.runAsync(() -> {
                Long userId = memberRespVo.getId();
                String nickname = memberRespVo.getNickname();
                CouponHistoryEntity couponHistory = new CouponHistoryEntity();
                couponHistory.setCouponId(couponId);
                couponHistory.setMemberId(userId);
                couponHistory.setMemberNickName(nickname);
                couponHistory.setGetType(1);
                couponHistory.setCreateTime(new Date());
                couponHistory.setUseStatus(0);
                couponHistoryService.save(couponHistory);
            });
            return R.ok("领取成功");
        }
        return R.error("优惠卷已经被领光啦");
    }

    @Override
    public R getMemberCoupons() {
        //获取当前用户
        MemberRespVo memberRespVo = LoginInterceptor.memberRespThreadLocal.get();
        //获取当前优惠卷领取记录
        List<CouponHistoryEntity> couponHistoryEntities =
                couponHistoryService.getBaseMapper()
                        .selectList(new QueryWrapper<CouponHistoryEntity>()
                                .eq("member_id", memberRespVo.getId()));
        //根据coupon_id查询优惠卷信息
        List<CouponVo> couponVos = couponHistoryEntities.stream().map(couponHistoryEntity -> {
            CouponEntity coupon = this.getById(couponHistoryEntity.getCouponId());
            CouponVo couponVo = new CouponVo();
            couponVo.setUseStatus(couponHistoryEntity.getUseStatus());
            if (coupon != null) {
                BeanUtils.copyProperties(coupon, couponVo);
            }
            return couponVo;
        }).collect(Collectors.toList());
        return R.ok().put("data", couponVos);
    }

    @Override
    public R getCouponCatch() {
        //获取当前用户
        MemberRespVo memberRespVo = LoginInterceptor.memberRespThreadLocal.get();
        List<CouponEntity> couponEntityList = this.baseMapper.selectList(null);
        if (CollectionUtils.isEmpty(couponEntityList)) {
            return R.ok();
        }
        List<CouponEntity> list = couponEntityList.stream()
                .filter(couponEntity ->
                        couponEntity.getReceiveCount() < couponEntity.getNum()
                                && couponEntity.getMemberLevel() < memberRespVo.getLevelId()
                                || couponEntity.getMemberLevel() == 0).collect(Collectors.toList());
        return R.ok().put("data", list);
    }
}